/**
 * 提现申请
 */
app.controller("withdrawApplyCtr", ["$scope", "eventServiceFactory", "fundsAccountService", function ($scope, eventServiceFactory, fundsAccountService) {
    /**
     * 监听到事件之后执行init模块。
     * @param data
     */
    $scope.init = function (data) {
        //初始化页面值
        $scope.initData(data);
    };
    var eventHandler = eventServiceFactory.createEventService();
    eventHandler.on('withdrawApplyData', $scope.init);

    /**
     * 初始化数据
     * @param data
     */
    $scope.initData = function (data) {
        //缓存主键值，默认页面共有。不再进行函数参数传递。
        $scope.thirdPayAccountId = data.thirdPayAccountId;
        $scope.accountInfo = data.accountInfo || {};
        //初始化页面值
        $scope.withdrawAmount = ''; //提现金额
        $scope.subbranch = '';  //收款账户
        $scope.bankName = '';
        $scope.bankNo = '';
        $scope.note = '';
        $scope.feeMoney = 0;    //手续费
        $scope.arrivedMoney = 0; //到账金额
        $scope.subbranchListData = '';
        if(Select.sharePool['select-subbranch-withdraw']){
            Select.sharePool['select-subbranch-withdraw'].clearData();
            Select.sharePool['select-subbranch-withdraw'].destroy();
        }

        $scope.withdrawForm.$setPristine();
        $scope.withdrawForm.$setUntouched();
    };

    /**
     * 全部提现
     */
    $scope.takeAll = function () {
        $scope.withdrawAmount = fundsAccountService.digital($scope.accountInfo.availableBalance);

        $scope.getFeeCheck();
    };

    /**
     * 获取手续费
     */
    $scope.getFeeCheck = function () {
        //校验数据正确性。是否超过了可提现余额
        /*var withdrawAmount = fundsAccountService.digital($scope.withdrawAmount),
            availableBalance = fundsAccountService.digital($scope.accountInfo.availableBalance);

        if (!withdrawAmount || !$scope.bankNo) {
            $scope.feeMoney = 0;
            $scope.arrivedMoney = 0;
            $scope.withdrawAmount = withdrawAmount.toFixed(2);    //页面显示0.00
            return;
        }
        if (withdrawAmount > availableBalance) {
            console.log('error: 提现金额超过可提现金额，请重新输入');
            return;
        }

        var config = {
            'urlParams': {
                "ccyCode": "string",    //货币类型code
                "custAcctId": "string",    //custAcctId 需要增加
                "custName": "string",
                "flag": "string",     //不传，置空
                "handFee": "string",    //不传，置空
                "note": "string",    //备注
                "orderid": "string",   //不传，置空
                "orig": "string",    //不传，置空
                "outAcctId": "string",    //收款账户cardNo
                "outAcctIdName": "string",    //收款账户银行名称
                "p2PCode": "string",  //不传，置空
                "sign": "string",  //不传，置空
                "thirdCustId": "string",
                "tranAmount": "string"
            }
        };
        fundsAccountService.getFeeCheck(config, function (res) {
            console.log('getFeeCheck-res', res);
            if (res.errorCode === 0) {

            }
        });*/
    };

    /**
     * 获取银行Card List
     */
    $scope.getSubbranchList = function () {
        if (!$scope.subbranchListData) {
            var config = {
                'seatParams': {
                    'thirdPayAccountId': $scope.thirdPayAccountId
                }
            };
            fundsAccountService.getBankVerdCardList(config, function (res) {
                $scope.subbranchListData = res.data;
                angular.forEach($scope.subbranchListData, function (item, index) {
                    if (item.cardNo) {
                        item.reName = item.bank + '（尾号' + (item.cardNo).slice(-4) + '）';
                    }
                });
            });
        }

        if ($scope.subbranchListData) {
            selectFactory({
                data: {
                    data: $scope.subbranchListData
                },
                defaultText: '请选择',
                id: 'select-subbranch-withdraw',
                defaultCount: 10000,
                showTextField: 'reName',
                isCreateNewSelect: true,
                attrTextModel: function (reName, data, item) {
                    $scope.subbranch = item.reName || '';
                    $scope.bankName = item.bank || '';
                    $scope.bankNo = item.cardNo || '';
                    $scope.getFeeCheck();    //获取手续费
                    $scope.$apply();
                }
            }).open();
        }
    };

    /**
     * 提现申请
     */
    $scope.submitWithdraw = function (event) {
        event.preventDefault();  //阻止跳转到第三方

        if (!$scope.withdrawAmount) {
            $scope.withdrawForm.withdrawAmount.$setDirty();
        }
        if (!$scope.subbranch) {
            $scope.withdrawForm.subbranch.$setDirty();
        }
        if (!$scope.note) {
            $scope.withdrawForm.note.$setDirty();
        }
        if (!$scope.withdrawForm.$valid) {
            return false;
        }

        var availableBalance = fundsAccountService.digital($scope.accountInfo.availableBalance),
            withdrawAmount = fundsAccountService.digital($scope.withdrawAmount);

        if(withdrawAmount > availableBalance){    //提现金额大于可用余额
            $(document).promptBox({isDelay: true, contentDelay: '提现金额不能超过可用余额!', type: 'errer', manualClose: true});
            return;
        }

        var signatureData = $scope.getSignature();

        var config = {
            'urlParams': {
                "flag": "1",
                "orderid": signatureData.orderid,
                "orig": signatureData.orig,
                "p2PCode": signatureData.p2PCode,
                "sign": "29a606cb4b7a4470ff5cfc54e1755253f3983c4c1a5f6b228efc964d7fe25a75f57d0983fd3136ee5f3eaa567d2c8fb2715198e3abe7c7e84924098cc2d939f478b7a99b06ab0c2917a8a4b39f6f2361b1b373b16dc4486c7aeea6ce3c7bb514c901b8595aee38906265a87c2f8169e96b1ab11611c8670c039aa4c5172f6015"
            }
        };
        fundsAccountService.withdrawCallback(config, function (res) {
            if (res.errorCode == 0) {
                $scope.goBack();
                $(document).promptBox({isDelay: true, contentDelay: '提现成功!', type: 'success'});
            } else {
                $(document).promptBox({isDelay: true, contentDelay: '提现失败!', type: 'errer', manualClose: true});
            }
        });



        /*var preventFlag = false;

         var arr = [
         {'key': 'name', 'require': true},
         {'key': 'orderid', 'require': true},
         {'key': 'type', 'require': true},
         {'key': 'p2PCode', 'require': true},
         {'key': 'p2PType', 'require': true},
         {'key': 'thirdCustId', 'require': true},
         {'key': 'custAccId', 'require': true},
         {'key': 'mobile', 'require': true},
         {'key': 'orig', 'require': true},
         {'key': 'returnurl', 'require': false},
         {'key': 'notifyUrl', 'require': true},
         {'key': 'channelType', 'require': false},
         {'key': 'idType', 'require': true},
         {'key': 'idNo', 'require': true},
         {'key': 'accNo', 'require': true},
         {'key': 'accName', 'require': true}
         ];

         for (var i = 0, l = arr.length; i < l; i++) {
         $('#' + arr[i].key).val(signatureData[arr[i].key]);    //隐藏表单域赋值。如：$('#type').val(signatureData.type);
         if (arr[i].require && !$.trim(signatureData[arr[i].key])) {    //必填字段为空
         preventFlag = true;
         }
         }

         $('#returnurl').val('https://www.baidu.com/');
         $('#notifyUrl').val('http://116.204.24.25:8888/notify');

         if (preventFlag) {    //阻止跳转到第三方
         event.preventDefault();
         } else {    //弹出 请在新开网银页面完成支付
         $scope.withdrawPrompt = true;
         }*/
    };

    /**
     * 提现前数字签名获取，从本系统中获取
     */
    $scope.getSignature = function () {
        var config = {
            'urlParams': {
                'custAcctId': $scope.accountInfo.custAcctId,
                'thirdCustId': $scope.accountInfo.thirdCustId,
                'custName': $scope.accountInfo.custName,
                'outAcctId': $scope.bankNo,
                'outAcctIdName': $scope.bankName,
                'ccyCode': $scope.accountInfo.currency,
                'tranAmount': $scope.withdrawAmount,
                'handFee': $scope.feeMoney,
                'note': $scope.note
            }
        };
        fundsAccountService.getSignature(config, function (res) {
            $scope.signatureData = res.data || {};
        });

        return $scope.signatureData;
    };

    /**
     * 提现结果
     * @param type
     */
    $scope.withdrawResult = function (type) {
        $scope.withdrawPrompt = false;

        //检测是否成功或者失败。

        if (type == 'failure') {    //点击失败。

        } else if (type == 'success') {    //点击成功。

        }
    };

    $scope.goBack = function(){
        $scope.$parent.block = 'accountDetail';
        //事件委派。
        eventHandler.dispatch('accountDetailData', {
            'thirdPayAccountId': $scope.thirdPayAccountId
        });
    };
}]);